<?php

namespace App\Console\Commands;

use App\Imports\NewCompanyStaffImport;
use App\Models\Company;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;

class HandleNewCompanyImport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'handle:import {--company= : name of company} {--file= : name of file}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $company = $this->option('company');
        $file = $this->option('file') ?? 'import_data_bxg.xls';
        if ($company && $file) {
            $this->info("Importing $company from $file");
            $company = Company::where('name', $company)->firstOrCreate(['name' => $company, 'code' => 'BXG', 'address' => '']);
            $this->info("Company $company->name created");
            $path = public_path('uploads/excel/' . $file);
            if (file_exists($path)) {
                Excel::import(new NewCompanyStaffImport($company->id), $path);
            } else {
                $this->error("File $path not found");
            }
        } else {
            $this->error('Please provide company and file name');
        }
    }
}
